/*
 * create:2016年4月8日 上午11:04:30
 * author:wangds  
 */
package com.cxkj.shop.model.shoppingcart;

import java.util.Collection;

import org.apache.commons.lang3.StringUtils;

import com.cxkj.shop.model.commodity.Commodity;
import com.cxkj.shop.model.grouppay.GroupPay;
import com.cxkj.shop.model.timelimitpay.TimeLimitPay;
import com.cxkj.shop.model.user.GegewuUser;
import com.cxkj.shop.model.user.User;
import com.cxkj.shop.utils.CommoditiesUtils;
import com.cxkj.shop.utils.GroupPayUtils;
import com.cxkj.shop.utils.LimitPayUtils;
import com.cxkj.shop.utils.UserUtils;

import net.wangds.common.GeneralParentObject;

/**
 * .
 * 
 * @author wangds
 *
 */
public final class ShoppingCartUtils {

  public static boolean addCommodity(ShoppingCart cart, String commodityId, int amount) {
    boolean res = false;
    try {
      if (cart == null || StringUtils.isBlank(commodityId) || amount == 0) {
        GeneralParentObject.staticLogger(ShoppingCartUtils.class).info("do nothing.");
        return true;
      }

      Collection<CommodityItem> list = cart.getCommodities();
      CommodityItem target = null;
      for (CommodityItem tmp : list) {
        if (StringUtils.equals(tmp.getCommodityId(), commodityId)) {
          target = tmp;
          break;
        }
      }
      if (target == null) {
        target = createCommodityById(commodityId);
        list.add(target);
      }

      int new_amount=target.getAmount() + amount;
      target.setAmount(new_amount>0?new_amount:0);
      res = true;
    } catch (Exception e) {
      GeneralParentObject.staticLogger(ShoppingCartUtils.class).error(e.getLocalizedMessage(), e);
    }
    return res;
  }
  
  public static boolean addScore(ShoppingCart cart, String commodityId, int amount) {
    boolean res = false;
    try {
      if (cart == null || StringUtils.isBlank(commodityId) || amount == 0) {
        GeneralParentObject.staticLogger(ShoppingCartUtils.class).info("do nothing.");
        return true;
      }

      Collection<CommodityItem> list = cart.getCommodities();
      CommodityItem target = null;
      for (CommodityItem tmp : list) {
        if (StringUtils.equals(tmp.getCommodityId(), commodityId)) {
          target = tmp;
          break;
        }
      }
      if (target == null) {
        target = createCommodityById(commodityId);
        target.setType(CommodityItem.TYPE_SCORE_PAY);
        list.add(target);
      }

      int new_amount=target.getAmount() + amount;
      target.setAmount(new_amount>0?new_amount:0);
      res = true;
    } catch (Exception e) {
      GeneralParentObject.staticLogger(ShoppingCartUtils.class).error(e.getLocalizedMessage(), e);
    }
    return res;
  }
  
  public static boolean addGroupPay(ShoppingCart cart, int grouppayId, int amount) {
    boolean res = false;
    try {
      if (cart == null || grouppayId<=0 || amount == 0) {
        GeneralParentObject.staticLogger(ShoppingCartUtils.class).info("do nothing.");
        return true;
      }

      Collection<CommodityItem> list = cart.getGrouppayments();
      CommodityItem target = null;
      for (CommodityItem tmp : list) {
        if (tmp.getGrouppayId()==grouppayId) {
          target = tmp;
          break;
        }
      }
      if (target == null) {
        GroupPay gp = GroupPayUtils.selectGroupPayById(grouppayId);
        target = new CommodityItem();
        target.setAmount(0);
        target.setCommodityCode(gp.getCommodityCode());
        target.setCommodityId(gp.getCommodityId());
        target.setCommodityName(gp.getCommodityName());
        target.setGprice(gp.getGprice());
        target.setGrouppayId(gp.getGrouppayId());
        target.setGscore(gp.getGscore());
        target.setMainImg(gp.getDesc());
        target.setPrice(gp.getPrice());
        target.setScore(gp.getScore());
        target.setType(CommodityItem.TYPE_GROUP_PAY);
        list.add(target);
      }

      int new_amount=target.getAmount() + amount;
      target.setAmount(new_amount>0?new_amount:0);
      res = true;
    } catch (Exception e) {
      GeneralParentObject.staticLogger(ShoppingCartUtils.class).error(e.getLocalizedMessage(), e);
    }
    return res;
  }
  
  public static boolean addTimelimitPay(ShoppingCart cart, int timelimitpayId, int amount) {
    boolean res = false;
    try {
      if (cart == null || timelimitpayId<=0 || amount == 0) {
        GeneralParentObject.staticLogger(ShoppingCartUtils.class).info("do nothing.");
        return true;
      }

      Collection<CommodityItem> list = cart.getTimelimitpayments();
      CommodityItem target = null;
      for (CommodityItem tmp : list) {
        if (tmp.getTimelimitpayId()==timelimitpayId) {
          target = tmp;
          break;
        }
      }
      if (target == null) {
        TimeLimitPay tlp = LimitPayUtils.seleTimeLimitPayById(timelimitpayId);
        target = new CommodityItem();
        target.setAmount(0);
        target.setCommodityCode(tlp.getCommodityCode());
        target.setCommodityId(tlp.getCommodityId());
        target.setCommodityName(tlp.getCommodityName());
        target.setGprice(0);
        target.setGrouppayId(0);
        target.setGscore(0);
        target.setMainImg(tlp.getDesc());
        target.setPrice(tlp.getPrice());
        target.setScore(tlp.getScore());
        target.setLprice(tlp.getLprice());
        target.setLscore(tlp.getLscore());
        target.setTimelimitpayId(timelimitpayId);
        target.setType(CommodityItem.TYPE_TIME_LIMIT_PAY);
        list.add(target);
      }

      int new_amount=target.getAmount() + amount;
      target.setAmount(new_amount>0?new_amount:0);
      res = true;
    } catch (Exception e) {
      GeneralParentObject.staticLogger(ShoppingCartUtils.class).error(e.getLocalizedMessage(), e);
    }
    return res;
  }

  /**
   * .
   * 
   * @author wangds 2016年4月8日 上午11:09:57.
   * @param commodityId
   * @return
   */
  private static CommodityItem createCommodityById(String commodityId) {
    CommodityItem res = new CommodityItem();
    res.setCommodityId(commodityId);
    
    Commodity co = CommoditiesUtils.selCommodityById(commodityId);
    res.setCommodityCode(co.getCommodityCode());
    res.setCommodityName(co.getCommodityName());
    res.setFreeType(CommodityItem.TYPE_NO_FREE);
    res.setGprice(0);
    res.setGrouppayId(0);
    res.setGscore(0);
    res.setMainImg(co.getDesc());
    res.setPrice(co.getPrice());
    res.setScore(co.getScore());
    res.setType(CommodityItem.TYPE_COMMODITY);
    res.setAmount(0);
    return res;
  }

  /**
   * .
   * @author wangds 2016年4月12日 上午11:46:39.
   * @param cart
   * @return 
   */
  public static Collection<CommodityItem> fetchCommodities(ShoppingCart cart) {
    return cart.getCommodities();
  }

  /**
   * .
   * @author wangds 2016年4月26日 下午5:41:34.
   * @param cart
   * @param id
   */
  public static void removeGroupPay(ShoppingCart cart, int grouppayId) {
    try {
      if (cart == null || grouppayId<=0 ) {
        GeneralParentObject.staticLogger(ShoppingCartUtils.class).info("do nothing.");
        return ;
      }

      Collection<CommodityItem> list = cart.getGrouppayments();
      for (CommodityItem tmp : list) {
        if (tmp.getGrouppayId()==grouppayId) {
          list.remove(tmp);
          break;
        }
      }
    } catch (Exception e) {
      GeneralParentObject.staticLogger(ShoppingCartUtils.class).error(e.getLocalizedMessage(), e);
    }
  }

  /**
   * .
   * @author wangds 2016年4月26日 下午5:51:28.
   * @param cart
   * @param id
   */
  public static void removeTimeLimitPay(ShoppingCart cart, int id) {
    try {
      if (cart == null || id<=0 ) {
        GeneralParentObject.staticLogger(ShoppingCartUtils.class).info("do nothing.");
        return ;
      }

      Collection<CommodityItem> list = cart.getTimelimitpayments();
      for (CommodityItem tmp : list) {
        if (tmp.getTimelimitpayId()==id) {
          list.remove(tmp);
          break;
        }
      }
    } catch (Exception e) {
      GeneralParentObject.staticLogger(ShoppingCartUtils.class).error(e.getLocalizedMessage(), e);
    }
  }
  
  
  /**
   * .
   * @author wangds 2016年4月26日 下午5:51:28.
   * @param cart
   * @param id
   */
  public static void removeCommodity(ShoppingCart cart, String id) {
    try {
      if (cart == null || StringUtils.isBlank(id) ) {
        GeneralParentObject.staticLogger(ShoppingCartUtils.class).info("do nothing.");
        return ;
      }

      Collection<CommodityItem> list = cart.getCommodities();
      for (CommodityItem tmp : list) {
        if (tmp.getCommodityId().equals(id)) {
          list.remove(tmp);
          break;
        }
      }
    } catch (Exception e) {
      GeneralParentObject.staticLogger(ShoppingCartUtils.class).error(e.getLocalizedMessage(), e);
    }
  }

  /**
   * .
   * @author wangds 2016年4月27日 下午12:19:01.
   * @param cart
   * @return
   */
  public static Collection<CommodityItem> fetchGroupPayments(ShoppingCart cart) {
    return cart.getGrouppayments();
  }
  
  /**
   * .
   * @author wangds 2016年4月27日 下午12:19:01.
   * @param cart
   * @return
   */
  public static Collection<CommodityItem> fetchTimeLimitPayments(ShoppingCart cart) {
    return cart.getTimelimitpayments();
  }
  
  /**
   * .
   * @author wangds 2016年4月27日 下午12:19:01.
   * @param cart
   * @return
   */
  public static Collection<CommodityItem> fetchScorePayments(ShoppingCart cart) {
    return cart.getScorepayments();
  }

  /**
   * .
   * @author wangds 2016年4月27日 下午4:54:23.
   * @param cart
   */
  public static void clear(ShoppingCart cart) {
    cart.getCommodities().clear();
    cart.getGrouppayments().clear();
    cart.getScorepayments().clear();
    cart.getScorepayments().clear();
  }

  /**
   * .
   * @author wangds 2016年4月27日 下午5:21:54.
   * @param openIdSession
   * @return
   */
  public static ShoppingCart createShoppingCart(String openId) {
    ShoppingCart res = new ShoppingCart();
    res.setUser(UserUtils.selectUserByOpenId(openId));
    return res;
  }

  /**
   * .
   * @author wangds 2016年5月5日 下午12:23:56.
   * @param cart
   */
  public static void checkFreebie(ShoppingCart cart) {
    int cnt = 0;
    Collection<CommodityItem> cos = null;
    try {
      if (cart.getGrouppayments().size() > 0 || cart.getScorepayments().size() > 0 || cart.getTimelimitpayments().size() > 0) {
        return;
      }
      cos = cart.getCommodities();
      boolean hasfreed = false;
      for (CommodityItem cur : cos) {
        cnt += cur.getAmount();
        if (cur.getFreeType() != CommodityItem.TYPE_NO_FREE) {
          hasfreed = true;
          cart.setTfo(false);
          cart.setOfo(false);
        }
      }
      if (hasfreed) {
        return;
      }
      if (cnt > 1) {
        cart.setOfo(true);
      }
      if (cnt > 3) {
        cart.setTfo(true);
      }
    } finally {
      //在购物车中修改
      if (cos != null) {
        if (cnt < 2) {
          for (CommodityItem cur : cos) {
            if (cur.getFreeType() == CommodityItem.TYPE_ONE_FREE_ONE) {
              cur.setFreeType(CommodityItem.TYPE_NO_FREE);
            }
          }
          cart.setOfo(false);
        }

        if (cnt < 4) {
          for (CommodityItem cur : cos) {
            if (cur.getFreeType() == CommodityItem.TYPE_THREE_FREE_ONE) {
              cur.setFreeType(CommodityItem.TYPE_NO_FREE);
            }
          }
          cart.setTfo(false);
        }
      }
    }
  }

  /**
   * .
   * @author wangds 2016年5月8日 下午10:36:26.
   * @param cart
   * @param user
   */
  public static void updateFreeCards(ShoppingCart cart, User user) {
    if(user instanceof GegewuUser){
      GegewuUser guser = (GegewuUser) user;
      if(guser.getPay3Free1Cart()<=0){
        cart.setTfo(false);
      }
      if(guser.getPay1Free1Cart()<=0){
        cart.setOfo(false);
      }
    }else{
      cart.setOfo(false);
      cart.setTfo(false);
    }
  }
}
